from .models import User
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

def jwt_response_payload_handler(token, user=None, request=None):
    '''
    定义jwt返回的字段
    '''
    return {
        'token': token,
        'id': user.id,
        'mobile': user.mobile,
        'username': user.username,
        'avatar': user.avatar,
    }

def get_user_by_accout(account):
    '''
    根据账号获取user
    '''
    users = User.objects.filter(Q(username=account)|Q(mobile=account))
    if not users:
        return None
    return users[0]

class MobileLogin(ModelBackend):
    '''
    自定义手机号或用户名登录
    '''
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_accout(username)

        if user is not None and user.check_password(password):
            return user